<template>
  <div class="basic-info-container">
    <div class="header-operations">
      <el-button 
        type="primary" 
        round 
       @click="open"
        icon="Plus"
      >
        新增
      </el-button>
      <el-button 
        type="danger" 
        round 
        :disabled="!selectedRows.length"
        
        icon="Delete"
      >
        删除
      </el-button>
      
      <div class="header-icons">
        <el-icon class="icon-btn" ><RefreshRight /></el-icon>
        <el-icon class="icon-btn" ><Setting /></el-icon>
        <el-icon class="icon-btn" ><Filter /></el-icon>
      </div>
    </div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="序号" width="80" />
      <el-table-column prop="shopNames" label="商品名称" width="120"/>
      <el-table-column prop="batch" label="生产批次" width="150" />
      <el-table-column prop="shelfLife" label="保质期(天)" width="100" />
      <el-table-column prop="productionLicense" label="生产许可证" width="180" />
      <el-table-column prop="manufacturers" label="生产企业" width="150" />
      <el-table-column prop="image" label="图片" width="100">
        <template #default="scope">
          <img 
      v-if="scope.row.image" 
      :src="scope.row.image" 
      class="table-image"
      style="width: 80px; height: auto;"
      @error="handleImageError(scope.$index)"
    >
    <el-empty v-else description="无图片" />
    </template>
</el-table-column>
      <el-table-column prop="completeness" label="信息完善度" width="120" />
      <el-table-column prop="createName" label="创建人" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="180" format="datetime" />
      <el-table-column prop="updateName" label="修改人" width="180" format="datetime" />
      <el-table-column prop="updateTime" label="修改时间" width="180" format="datetime" />
      
      <el-table-column fixed="right" label="操作" min-width="200">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            size="small"
            @click="(scope.row)"
          >
            详情
          </el-button>
          
          <el-button 
            link 
            type="success" 
            size="small"
            @click="(scope.row)"
          >
            修改
          </el-button>
          
          <el-button 
            link 
            type="warning" 
            size="small"
            @click="(scope.row)"
          >
            导出溯源码
          </el-button>
          
          <el-button 
            link 
            type="danger" 
            size="small"
            @click="(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogFormVisible" title="基本信息" width="500">
      <el-form 
        :model="form" 
        :rules="formRules"
        ref="formRef"
        label-width="120px"
      >
        <el-form-item label="商品名称" prop="shopName">
          <el-select 
          v-model="obj.shopName" 
            placeholder="请选择商品"
            filterable 
            :options="shopOptions" 
          >
            <el-option 
            v-for="option in shopOptions"
      :key="option.id"  
      :label="option.shopName"
      :value="option.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="生产批次" prop="batch">
          <el-input 
            v-model="obj.batch" 
            maxlength="30"
            placeholder="请输入生产批次"
          />
        </el-form-item>

        <el-form-item label="保质期(天)" prop="shelfLife">
          <el-input 
            v-model.number="obj.shelfLife" 
            type="number"
            min="1"
            max="3650"
            placeholder="请输入保质期（天）"
          />
        </el-form-item>

        <el-form-item label="生产许可证" prop="productionLicense">
  <el-input 
    v-model="obj.productionLicense" 
    maxlength="30"
    placeholder="请输入生产许可证号"
    @input="handleProductionLicenseInput"
  />
</el-form-item>

<el-form-item label="生产企业" prop="manufacturers">
  <el-input 
    v-model="obj.manufacturers" 
    maxlength="30"
    placeholder="请输入生产企业名称"
    @input="filterManufacturersInput"
  />
</el-form-item>

        <el-form-item label="封面图">
          <el-upload
    class="avatar-uploader"
    action="https://localhost:7106/api/traceability/unload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    v-model="obj.image" 
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
  </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="primary" 
            @click="add()"
          >
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="obj1.index"
      v-model:page-size="obj1.size"
      :page-sizes="[1, 3, 5, 15]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="obj1.zcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { 
  ref, reactive, computed, onMounted, watch, 
} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { 
  Delete, RefreshRight, Setting, Filter, Plus 
} from '@element-plus/icons-vue'
import { th, tr } from 'element-plus/es/locales.mjs'

// 类型定义
interface Product {
  id: number
  shopName: number
  productionBatch: string
  shelfLife: number
  productionLicense: string
  manufacturers: string
  coverImage: string
  completeness: string
  creator: string
  createTime: string
}

interface ShopOption {
  id: number
  shopName: string
  enabled: boolean
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// 状态管理
const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const selectedRows = ref<Product[]>([])
const tableData = ref<Product[]>([])
const shopOptions = ref<ShopOption[]>([])


const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 50,
  total: 0
})


const formss = reactive({ productionLicense: '' });

// 输入时过滤非数字、字母内容
const handleProductionLicenseInput = (val: string) => {
  formss.productionLicense = val.replace(/[^0-9a-zA-Z]/g, '');
};
const form1 = reactive({ manufacturers: '' });

// 输入过滤：仅保留中文、字母（大小写），过滤特殊字符
const filterManufacturersInput = (val: string) => {
  form1.manufacturers = val.replace(/[^\u4e00-\u9fa5a-zA-Z]/g, ''); // 允许中文+字母
  // 如需允许空格：/[^\u4e00-\u9fa5a-zA-Z\s]/g
};


//  表单校验规则
const formRules: FormRules = {
   shopName: [{ required:true, message: '商品名称不能为空', trigger: 'change' }],
 
  //2生产批次
  batch: [
    { required:false, message: '请输入生产批次', trigger: 'blur' },
    { maxlength: 30, message: '最多输入 30 位字符', trigger: 'blur' }
  ],
 //3保质期
 shelfLife: [
    { required: true, message: '请输入生产批次', trigger: 'blur' },
    { type: 'number', message: '仅允许输入数字', trigger: 'blur' },
    { max: 5, message: '最多输入 5 位数字', trigger: 'blur' }
  ],
  //4生产许可证
  productionLicense: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
    { 
      pattern: /^[0-9a-zA-Z]{0,30}$/, 
      message: '仅允许输入数字和大小写字母,最多30位', 
      trigger: 'blur' 
    },
    { maxlength: 30, message: '最多输入30位字符', trigger: 'blur' }
  ],
  //5生产 企业
  manufacturers: [
    { required: true, message: '请输入生产企业', trigger: 'blur' }, // 修正提示文案
    { 
      pattern: /^[\u4e00-\u9fa5a-zA-Z]{0,30}$/, // 严格中文+字母，不包含空格/特殊符号
      message: '仅允许输入中文和字母，最多30位', 
      trigger: 'blur' 
    },
    { maxlength: 30, message: '最多输入30位字符', trigger: 'blur' }
  ],
}



// 生命周期
onMounted(() => {
  show();
  fetchShopOptions()
})
const obj1=reactive({
    index:1,
    size:15,
    zcount:0,
    zpage:0, 
    shopname:""
})
watch(obj1,()=>{
  show();
  fetchShopOptions();
})
const handleImageError = (index: number) => {
  const defaultImageUrl = 'https://localhost:7106/api/traceability/unload'; // 替换为实际默认图地址
  tableData.value[index].image = defaultImageUrl;
}
const handleImageUrl = (url: string) => {
  if (!url.startsWith('http')) return `https://your-domain.com${url}`; // 替换为实际域名
  return url;
}
const show=()=>{
  axios({
    url:"https://localhost:7050/api/GetRibbitersE/Showjiben?index="+obj1.index+"&size="+obj1.size,
    method:"get",
    params:obj1
  })
  .then((res)=>{ 
    console.log(res);
    tableData.value=res.data.data.items.map(items => ({
     ...items,
      image: handleImageUrl(items.image) // 处理每个元素的图片链接
    }));
    obj1.zcount=res.data.data.totalCount
    obj1.zpage=res.data.data.totalPage
    image: handleImageUrl(obj.image) // 处理图片链接
  })
  .catch((err)=>{
    console.log(err);
  })
}


//#region 显示商品

const fetchShopOptions = async () => {
  axios({
    url: `https://localhost:7050/api/GetRibbitersE/ShowShop`,
    method: 'get',
  })
  .then((res) => {
    console.log(res);
    shopOptions.value = res.data.data;
    
  })
  .catch((err) => {
    console.log(err);
    ElMessage.error('商品列表加载失败');
  });
}
//#endregion
// 对话框操作
const open=()=>{
  dialogFormVisible.value=true;
}
const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const form = reactive({
  name: '',
  region: '',
  date1: '',
  date2: '',
  delivery: false,
  type: [],
  resource: '',
  desc: '',
})
import {useCounterStore} from "@/stores/counter"
const store=useCounterStore();
//#region 添加
const obj=reactive({
  "shopName":0,
  "batch": "",
  "shelfLife":0,
  "productionLicense": "",
  "manufacturers": "",
  "image": "",
  "completeness": "",
   "createName":store.ccstore.nickName,
});
const add=()=>{
axios({
  url:"https://localhost:7106/api/traceability/Addtraceability",
  method:"post",
  data:obj,
})
.then((res)=>{
  console.log(res);
 if(res.data.code===100)
 {
  ElMessage({
        type: 'success',
        message: '添加成功',
      })
 }
})
.catch((err)=>{
  console.log(err);
  ElMessage({
        type: 'info',
        message: '添加失败',
      })
})
}
//#endregion
//#region 图片上传
import type { UploadProps } from 'element-plus'

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // 假设后端返回的图片路径在response.data中
  const imgUrl = response.data; 
  imageUrl.value = imgUrl;
  obj.image = imgUrl;
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('请上传jpg格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('不要超过 2MB!')
    return false
  }
  return true
}
//#endregion
//分页
import type { ComponentSize } from 'element-plus'
const currentPage1 = ref(5)
const currentPage2 = ref(5)
const currentPage3 = ref(5)
const currentPage4 = ref(4)
const pageSize2 = ref(100)
const pageSize3 = ref(100)
const pageSize4 = ref(100)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  obj1.zcount=val;
  show();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  obj1.zpage=val;
  show();
}
//删除
const deleteItem = (itemId) => {
  ElMessageBox.confirm(
    '确认要删除该记录吗？',
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
 .then(() => {
    axios({
      url: "https://localhost:7106/api/traceability/Deletetraceability",
      method: "post",
      data: { id: itemId } 
    })
   .then((res) => {
      console.log(res);
      if (res.data.code === 400) {
        ElMessage({
          type:'success',
          message: '删除成功',
        });
      }
    })
   .catch((err) => {
      console.log(err);
      ElMessage({
        type: 'info',
        message: '删除失败',
      });
    });
  })
 .catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除操作',
    });
  });
};
</script>

<style scoped>
.basic-info-container {
  padding: 20px;
}
.avatar {
  object-fit: cover; /* 图片填充方式 */
  border-radius: 4px; /* 可选圆角 */
}
.header-operations {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-icons .icon-btn {
  margin-left: 15px;
  cursor: pointer;
  color: var(--el-color-text-Secondary);
}

.header-icons .icon-btn:hover {
  color: var(--el-color-primary);
}

.el-table .cell {
  padding: 12px 8px;
  font-size: 0.9em;
}

.el-table__fixed-right {
  right: 0;
}

.el-dialog__body {
  padding: 20px 40px;
}

.avatar-uploader {
  width: 200px;
  height: 200px;
  margin: 0 auto;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.demo-pagination-block {
  margin-top: 20px;
}
.table-image {
    object-fit: cover;
    border-radius: 4px;
}
</style>    
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>